﻿using System;
using System.Windows.Forms;
using App.Modelo.Menu;
using App.Persistencia;
using App.Seguridad.Vista.Forms;
using App.Seguridad.Vista.Menu;
using App.SolInf.Modelo;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;
using App.Modelo.Attributes;
using Microsoft.SqlServer.Management.Smo;


namespace App.SolInf.Vista
{
    [Formulario("Backup")]
    public partial class BackupForm : Form
    {
        SqlConnectionStringBuilder connection;
        Server server;
        
        public string UserName { get; set; }
        public string Password { get; set; }


        public BackupForm()
        {

            InitializeComponent();
            openFileDialog1.InitialDirectory
                = saveFileDialog1.InitialDirectory
                  = AppDomain.CurrentDomain.BaseDirectory;


            var controladorBoton = new MenuControladoraBotonera
            {
                Controls = flowLayoutPanel1.Controls,
                Model = new MenuContenedor(new MenuBaseItem[] {
                        new MenuBoton("Generar backup", "backupNew", "Backup/alta"),
                        new MenuBoton("Restituir backup", "backupRestore", "Backup/modificar"),
                    })
            };

            controladorBoton.ExecuteCommand += new EventHandler<MenuEjecutarComandoEventArgs>(controladorBoton_ExecuteCommand);
        }


        void controladorBoton_ExecuteCommand(object sender, MenuEjecutarComandoEventArgs e)
        {
            if (e.Item.Command == "Backup/alta")
            {
                _generar();
            }
            else if (e.Item.Command == "Backup/modificar")
            {
                _restaurar();
            }
        }

        [Comando("ver")]
        public void ver()
        {
            Show();
        }

        [Comando("alta")]
        public void alta()
        {
            Show();
        }

        [Comando("modificar")]
        public void modificar()
        {
            Show();
        }

        ServerConnection serverConnection;
        public ServerConnection ServerConnection
        {
            get
            {
                if (serverConnection == null)
                {
                    var conn = new ServerConnection(Connection.DataSource);

                    try
                    {
                        conn.Connect();

                        serverConnection = conn;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }

                } 

                return serverConnection;

            }
        }
        public Server Server
        {
            get
            {
                if (null == server && ServerConnection != null)
                    server = new Server(ServerConnection);
                return server;
            }
            set
            {
                server = value;
            }
        }
        
        public SqlConnectionStringBuilder Connection
        {
            get
            {
                if (connection == null)
                {
                    var r = new Repositorio();

                    connection = new SqlConnectionStringBuilder(r.Connection.ConnectionString);
                }
                    

                return connection;
            }
            set
            {
                connection = value;
            }
        }


        private void _generar()
        {
            if (Server == null)
                return;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {

                var bdi = new BackupDeviceItem(saveFileDialog1.FileName, DeviceType.File);

                var backup = new Backup { Database = Connection.InitialCatalog, Initialize = true };

                backup.Devices.Add(bdi);
                
                try
                {
                    backup.SqlBackup(Server);
                    MessageBox.Show("Backup generado\n" + saveFileDialog1.FileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error al generar el backup\n" + ex.Message);
                }
            }
        }


        private void _restaurar()
        {
            if (Server == null)
                return;

            if (MessageBox.Show("Se reiniciara la aplicacion despues de restaurar\nDesea continar?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                return;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {

                var r = new Restore();
                r.Database = Connection.InitialCatalog;

                r.Devices.Add(new BackupDeviceItem(openFileDialog1.FileName, DeviceType.File));
                r.ReplaceDatabase = true;
                Server.KillAllProcesses(r.Database);
                r.Wait();
                try
                {
                    r.SqlRestore(Server);
                    MessageBox.Show("Backup restablecido\n" + openFileDialog1.FileName + "\nSe reiniciara la aplicacion" );
                    Application.Restart();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error al restituir el backup\n" + ex.ToString());
                }
            }
        }

    }
}
